package com.whisper.application.app.web.service;

import com.whisper.application.service.domain.VrUser;
import com.whisper.cache.service.CacheService;
import com.whisper.common.exception.user.UserPasswordNotMatchException;
import com.whisper.common.exception.user.UserPasswordRetryLimitExceedException;
import com.whisper.common.security.context.AuthenticationContextHolder;
import com.whisper.common.security.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

import static com.whisper.common.excel.utils.DictUtils.getFrontCacheKey;

@Service
public class PasswordService {

    @Autowired
    private CacheService cacheService;

    /**
     * 最大重试次数
     */
    @Value(value = "${user.password.maxRetryCount}")
    private int maxRetryCount;

    /**
     * 锁定时间
     */
    @Value(value = "${user.password.lockTime}")
    private int lockTime;

    public void validate(VrUser user)
    {
        Authentication usernamePasswordAuthenticationToken = AuthenticationContextHolder.getContext();
        String username = usernamePasswordAuthenticationToken.getName();
        String password = usernamePasswordAuthenticationToken.getCredentials().toString();

        Integer retryCount = cacheService.getCacheObject(getFrontCacheKey(username));

        if (retryCount == null)
        {
            retryCount = 0;
        }

        if (retryCount >= Integer.valueOf(maxRetryCount).intValue())
        {
            throw new UserPasswordRetryLimitExceedException(maxRetryCount, lockTime);
        }

        if (!matches(user, password))
        {
            retryCount = retryCount + 1;
            cacheService.setCacheObject(getFrontCacheKey(username), retryCount, lockTime, TimeUnit.MINUTES);
            throw new UserPasswordNotMatchException();
        }
        else
        {
            clearLoginRecordCache(username);
        }
    }

    public boolean matches(VrUser user, String rawPassword)
    {
        return SecurityUtils.matchesPassword(rawPassword, user.getPassword());
    }

    public void clearLoginRecordCache(String loginName)
    {
        if (cacheService.hasKey(getFrontCacheKey(loginName)))
        {
            cacheService.deleteObject(getFrontCacheKey(loginName));
        }
    }
}
